package com.cheng.reggie.controller;

import com.cheng.reggie.common.R;
import com.cheng.reggie.entity.ShoppingCart;
import com.cheng.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired(required = false)
    private ShoppingCartService shoppingCartService;

    @PostMapping("/sub")
    public R<ShoppingCart> update(@RequestBody  ShoppingCart shoppingCart,HttpSession session) {
        Long id = (Long) session.getAttribute("user");
        shoppingCart.setUserId(id);
        //调用service数量方法
         shoppingCartService.update(shoppingCart);
         return R.success(shoppingCart);
    }



    @RequestMapping("/add")
    public R<ShoppingCart> addCart(@RequestBody ShoppingCart shoppingCart , HttpSession session){
            //1。接受请求数据封装到ShoppingCart对象
            //2.获取登录数据用户的id封装ShoppingCart对象在
        Long id = (Long) session.getAttribute("user");
        shoppingCart.setUserId(id);
        //调用业务进行添加购物车操作
        ShoppingCart shoppingCartNew = shoppingCartService.addCart(shoppingCart);
        //4.设置返回数据,将购物车对象返回
        return R.success(shoppingCartNew);
    }

    //查询指定用户的购物车集合数据
    @RequestMapping("/list")
    public R<List<ShoppingCart>> findAllByUserId(HttpSession session){
        //1.获取登录用户id
        Long userId = (Long) session.getAttribute("user");
        //调用业务层获取用户购物车集合数据
        List<ShoppingCart> shoppingCartList = shoppingCartService.findAllByUserId(userId);
        //返回购物车集合数据
        return R.success(shoppingCartList);
    }

    @DeleteMapping("/clean")
    public R<String> clean(HttpSession session){
        //获取登录用户id
        Long userId = (Long) session.getAttribute("user");
        shoppingCartService.clean(userId);;
        return R.success("清空购物车成功!");
    }
}
